package xyz.jcat.seata.example.order.service.impl;

import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xyz.jcat.common.exception.BusinessException;
import xyz.jcat.common.util.JsonUtils;
import xyz.jcat.mybatis.ServiceImpl;
import xyz.jcat.seata.example.api.dto.SaleDto;
import xyz.jcat.seata.example.order.domain.dao.IOrderDao;
import xyz.jcat.seata.example.order.domain.po.OrderPo;
import xyz.jcat.seata.example.order.service.IOrderService;

import java.util.Date;
import java.util.Objects;

/**
 *
 * @author yueyue
 * auto on 2022-03-16 00:43:38
 */
@Slf4j
@Service
public class OrderService extends ServiceImpl<IOrderDao, OrderPo> implements IOrderService {

    @Override
    public void addOrder(OrderPo order) {
        order.setCreateTime(new Date());
        order.setStatus(0);
        dao.insert(order);
    }

    @Override
    public boolean addOrderCommit(BusinessActionContext context) {
        OrderPo order = getOrderByAddOrderBusinessActionContext(context);
        order = getById(order.getId());
        if(Objects.equals(order.getStatus(), 0)) {
            order.setStatus(1);
            updateById(order);
            return true;
        }
        log.error("订单状态异常[addOrderCommit], orderId = ()", order.getId());
        return false;
    }

    @Override
    public boolean addOrderRollback(BusinessActionContext context) {
        OrderPo order = getOrderByAddOrderBusinessActionContext(context);
        deleteById(order.getId());
        return true;
    }

    @Override
    public Long getOrderId() {
        return Long.valueOf(dao.selectCount(null)+1);
    }

    private OrderPo getOrderByAddOrderBusinessActionContext(BusinessActionContext context) {
        Object saleDtoJson = context.getActionContext("order");
        return JsonUtils.parseObject(saleDtoJson, OrderPo.class);
    }
}
